package cn.wxz1997.permission.config;

import cn.wxz1997.permission.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 认证失败处理
 * @Author: wxz1997
 * @Date 18-8-7下午9:33
 */
@Slf4j
@Component
public class MyFailureHandler implements AuthenticationFailureHandler{
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("进入认证失败处理器！");
        //httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        String msg = null;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            msg = "用户名或密码输入错误，登录失败!";
        } else {
            msg = "登录失败!" + e;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String result = objectMapper.writeValueAsString(Result.error(msg));
        out.write(result.toString());
        out.flush();
        out.close();
    }
}
